<template>
  <div
    class="order-list-container list-container"
    v-loading.fullscreen.lock="loading"
  >
    <!-- 引导使用 -->
    <!-- <div id="order-list"></div> -->

    <!-- 搜索区域 -->
    <div
      ref="tableHeaderContainer"
      class="order-list-search-group-container bg-w list-search-group-container"
      style="display: block"
    >
      <div class="task-list-header-search" style="align-items: center">
        <form class="task-flex task-ai" onsubmit="return false;">
          <div
            class="base-search-group input-with-append-search task-flex task-ai"
          >
            <el-input
              v-model="searchModel.keywords"
              :placeholder="placeholder"
              class="task-with-input task-mr12"
            >
              <!-- <i slot="prefix" class="el-input__icon el-icon-search"></i> -->
              <el-select
                v-model="searchCondition"
                slot="prepend"
                :placeholder="$t('common.base.pleaseSelect')"
                class="task-with-select"
              >
                <el-option :label="$t('event.detail.text3')" value="order"></el-option>
                <el-option :label="$t('goods.detail.productInfo')" value="goods"></el-option>
              </el-select>
              <el-button
                type="primary"
                slot="append"
                @click="
                  searchModel.pageNum = 1;
                  handleSearch();
                  trackEventHandler('search');
                "
                native-type="submit"
              >
                {{$t('common.base.search')}}
              </el-button>
            </el-input>
            <el-button type="plain-third" @click="resetParams">{{$t('common.base.reset')}}</el-button>
          </div>

          <!-- 老版本高级搜索 -->
          <div class="base-search">
            <div
              @click.self.stop="panelSearchAdvancedToggle"
              class="advanced-search-visible-btn"
            >
              <i class="iconfont icon-filter task-mr4"></i>
              {{$t('common.base.advancedSearch')}}
            </div>
          </div>
          <!-- 新版本高级搜索，由于数据不在es上先使用老版本高级搜索，上es以后再换回来 -->
          <!-- <div :class="['advanced-search-visible-btn', 'bg-w']">
            <advanced-search
              :fields="searchFieldInfo"
              :has-create="false"
              :has-save="false"
              @search="handleAdvancedSearch"
            />
          </div> -->
        </form>
      </div>

      <div class="task-list-header-nav">
        <div class="task-filter-item">
          <div class="task-font14 task-c7 state task-c8">{{$t('order.detailV2.orderStatus')}}：</div>
          <div class="list list-crate">
            <div class="list-item task-flex task-ai">
              <div
                v-for="(item, index) in selectStateList"
                :key="index"
                class="task-nav-create"
                :class="{
                  'task-c2': selectState === item.value,
                  'task-padding-0': selectState === item.value,
                }"
                @click.stop="handleStateChange(item.value)"
              >
                <span class="actived" style="margin: 0 12px 8px 0; display: inline-block;">{{ item.label }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="order-list-section list-section">
      <div ref="tableDoContainer" class="operation-bar-container">
        <div class="">
          <el-button
            type="plain-third"
            @click="batchApprove"
            v-if="batchApproveAuth"
          >
            {{$t('order.component.batchApprove')}}
          </el-button>
        </div>
        <div class="action-button-group bg-w" v-if="exportPermission">
          <el-dropdown trigger="click">
            <div
              class="task-ai task-flex task-font14 task-c6 cur-point bg-w"
              @click="trackEventHandler('moreAction')"
            >
              <span class="task-mr4 task-ml4">{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <div @click="handleExport(false)">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div @click="handleExport(true)">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <!-- 模拟表格 -->
      <div
        ref="orderTableRef"
        :class="[
          'order-table-container',
          hiddenScrollbar && 'hidden-scrollbar',
        ]"
      >
        <div
          class="order-table bg-w pad-l-16 pad-r-16"
          :style="{ 'min-height': tableContainerHeight }"
        >
          <div class="order-table-header order-table-row">
            <div class="order-table-col">{{$t('goods.detail.productInfo')}}</div>
            <div class="order-table-col">{{$t('order.detailV2.productType')}}</div>
            <div class="order-table-col">{{$t('common.fields.catalog.displayName')}}</div>
            <div class="order-table-col">{{$t('order.detailV2.serviceMethod')}}</div>
            <div class="order-table-col">{{$t('common.base.quantity')}}</div>
            <div class="order-table-col">{{$t('order.detailV2.amountPaid')}}</div>
            <div class="order-table-col">{{$t('common.base.operation')}}</div>
          </div>

          <template v-if="Array.isArray(page.list) && page.list.length > 0">
            <div
              class="order-table-card el-row"
              v-for="(item, index) in page.list"
              :key="item.orderId"
            >
              <div class="order-table-card-header">
                <div class="order-table-card-header-content">
                  <div>
                    <el-checkbox
                      v-model="item.checked"
                      @change="handleCheckboxChange(index)"
                    ></el-checkbox>
                    {{$t('common.fields.orderSerialNumber.displayName')}}：
                    <span
                      class="order-btn"
                      @click="handleOpenOrderMenuTab(item)"
                      >{{ item.orderNum }}</span
                    >
                    <span
                      v-if="refundArr.includes(item.refundState)"
                      class="order-status refund-status"
                      :style="{background: getRefundStatusColor(item.refundState)}"
                    >
                      {{ getRefundStatusStr(item.refundState) }}
                    </span>
                  </div>
                  <div>{{$t('order.detailV2.orderTime')}}：{{ item.placeOrderDate | formatTime }}</div>
                  <div class="logistics-state">
                    <span>{{$t('order.detailV2.orderStatus')}}：</span>
                    <el-tooltip
                      v-if="item.logisticsState === 2 && item.underApproval"
                      class="item"
                      effect="dark"
                      :content="$t('order.tips.tooltipText3')"
                      placement="top"
                    >
                      <i class="iconfont icon-warning-circle-fill"></i>
                    </el-tooltip>
                    <span
                      class="order-status"
                      :style="getOrderStatusColor(item.logisticsState)"
                    >
                      {{ getOrderStatusStr(item.logisticsState) }}
                    </span>
                  </div>
                  <!-- 待付款和已取消没有支付方式 -->
                  <div
                    class="pay-type"
                    v-if="
                      item.logisticsState !== 1 && item.logisticsState !== 5
                    "
                  >
                    <span>{{$t('common.form.preview.pay.payMethod')}}：</span>
                    <img
                      v-if="[1, 2, 3].includes(item.payType)"
                      :src="payIconList[item.payType - 1]"
                      :style="{ width: item.payType === 3 ? '18px' : '16px' }"
                      alt=""
                    />
                    <span>{{ getPayTypeStr(item.payType) }}</span>
                  </div>
                  <div></div>
                </div>

                <div v-if="editedPermission && item.refundState != 1">
                  <!-- 当订单为“待付款”、“待发货”、“已发货”时才展示 -->
                  <el-tooltip
                    trigger="hover"
                    placement="top"
                    effect="dark"
                    v-if="
                      item.logisticsState === 1 ||
                        item.logisticsState === 2 ||
                        item.logisticsState === 3
                    "
                    :content="$t('order.detailV2.modifyOrder')"
                  >
                    <i
                      @click="openDialog('edit', item)"
                      class="iconfont icon-edit-square1 order-btn"
                    ></i>
                  </el-tooltip>
                  <!-- 当订单为“待付款”、“待发货”时才展示 -->
                  <el-tooltip
                    trigger="hover"
                    placement="top"
                    effect="dark"
                    v-if="
                      item.logisticsState === 1 || item.logisticsState === 2
                    "
                    :content="$t('order.detailV2.cancelOrder')"
                  >
                    <i
                      @click="handleCancelOrder(item.orderId)"
                      class="iconfont icon-quxiaodingdan order-btn"
                    ></i>
                  </el-tooltip>
                </div>
              </div>

              <div
                class="order-table-card-main order-table-row"
                :style="{
                  height: `${
                    ((item.commodityInfoList &&
                      item.commodityInfoList.length) ||
                      1) * 80
                  }px`,
                }"
              >
                <div class="order-table-col">
                  <div
                    v-for="(subItem, subIndex) in item.commodityInfoList"
                    :key="`${subItem.originCode}_${index}_${subIndex}`"
                    class="card-item"
                  >
                    <el-image
                      :src="subItem.image || goodsDefault"
                      @click.stop="previewImg(subItem.image)"
                    ></el-image>
                    <div>
                      <span class="overHideCon-2">{{ subItem.commodityName }}</span>
                      <span @click="handleOpenGoodsMenuTab(subItem)">{{
                        subItem.originCode
                      }}</span>
                    </div>
                  </div>
                </div>
                <div class="order-table-col">
                  <div
                    v-for="(subItem, subIndex) in item.commodityInfoList"
                    :key="`${subItem.originType}_${index}_${subIndex}`"
                    class="card-item"
                  >
                    {{ getOriginType(subItem.originType) }}
                  </div>
                </div>
                <div class="order-table-col">
                  <div
                    v-for="(subItem, subIndex) in item.commodityInfoList"
                    :key="`${subItem.originCategory}_${index}_${subIndex}`"
                    class="card-item"
                  >
                    {{ subItem.originCategory }}
                  </div>
                </div>
                <div class="order-table-col">
                  <div
                    v-for="(subItem, subIndex) in item.commodityInfoList"
                    :key="`${subItem.serviceType}_${index}_${subIndex}`"
                    class="card-item"
                  >
                    {{ getServiceTypeStr(subItem.serviceType) }}
                  </div>
                </div>
                <div class="order-table-col">
                  <div
                    v-for="(subItem, subIndex) in item.commodityInfoList"
                    :key="`${subItem.count}_${index}_${subIndex}`"
                    class="card-item"
                  >
                    {{ subItem.count }}
                  </div>
                </div>
                <!-- 实付金额 -->
                <div class="order-table-col">
                  <div class="card-item">
                    <span>{{ numFilter(item.payAmount) }}</span>
                    <span></span>
                    <span
                      v-if="
                        (item.logisticsState === 3 ||
                          item.logisticsState === 4) &&
                        item.haveLogisticsInfo
                      "
                      @click="openDialog('logistics', item)"
                      >{{$t('common.form.preview.sparepart.colum16')}}</span
                    >
                  </div>
                </div>
                <div class="order-table-col">
                  <base-operation-btns
                    class="card-item"
                    :extra-data="{item}"
                    :btn-array="orderMainBtns">
                  </base-operation-btns>
                </div>
              </div>

              <div class="order-table-card-footer el-row">
                <i class="iconfont icon-fdn-user"></i>
                <span
                  >{{$t('order.component.consignee')}}：{{ `${item.memberName} ${item.memberPhone}` }}</span
                >
                <span
                  v-if="item.remarks && item.remarks.length <= 20"
                  class="remarks"
                  >{{$t('order.detailV2.buyerMessage')}}：{{ item.remarks }}</span
                >
                <el-tooltip
                  v-else-if="item.remarks && item.remarks.length > 20"
                  effect="dark"
                  :content="item.remarks"
                  placement="top"
                >
                  <span class="remarks"
                    >{{$t('order.detailV2.buyerMessage')}}：{{ `${item.remarks.substring(0, 20)}...` }}</span
                  >
                </el-tooltip>
              </div>
            </div>
          </template>
          <template v-else>
            <BaseListForNoData
              class="order-table-no-data"
              :style="{ height: noDataHeight }"
              v-show="!loading"
              :notice-msg="$t('common.base.noData')"
            ></BaseListForNoData>
          </template>
        </div>
      </div>

      <!-- 分页区域 -->
      <div
        ref="tableFooterContainer"
        class="table-footer bbx-normal-table-footer-10"
      >
        <div class="list-info">
          {{$t('goods.list.total')}} <span class="level-padding">{{ page.totalElements }}</span> {{$t('common.base.record')}}
          <template v-if="multipleSelection && multipleSelection.length > 0">
            {{$t('part.list.text2')}}
            <span
              class="product-selected-count"
              @click="multipleSelectionPanelShow = true"
              >{{ multipleSelection.length }}</span
            >{{$t('common.base.piece')}}
          </template>
        </div>
        <el-pagination
          class="product-table-pagination"
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="page.pageSize"
          :current-page="page.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="page.totalElements"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 老版本高级搜索-->
    <base-search-drawer
      :show.sync="visible"
      @reset="resetParams"
      @search="handleAdvancedSearch"
      @changeWidth="setAdvanceSearchColumn"
    >
      <base-search-panel
        ref="searchPanel"
        :column-num="columnNum"
        :fields="searchFieldInfo"
      />
    </base-search-drawer>
    <!-- 导出弹窗 -->
    <base-export-group
      ref="exportPanelRef"
      :alert="exportAlert"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :group="true"
      :validate="checkExportCount"
      :needchoose-break="false"
      method="post"
      :action="OrderExport"
      :is-show-export-tip="isOpenData"
    />
    <!-- 快递发货弹窗 -->
    <DeliverGoodsDialog ref="deliverGoodsRef" @reloadPage="reloadPage" />
    <!-- 上门服务弹窗 -->
    <OnsiteServicesDialog ref="onsiteServicesRef" @reloadPage="reloadPage" />
    <!-- 修改订单弹窗 -->
    <EditOrderDialog ref="editOrderRef" @reloadPage="reloadPage" />
    <!-- 物流信息弹窗 -->
    <LogisticsInfoDialog ref="logisticsInfoRef" />
    <OrderApproveDialog ref="orderApproveDialog" @reloadPage="reloadPage"/>

    <el-dialog :title="$t('order.component.batchApprove')" :visible.sync="batchApproveDialog" @close="saveDialogClosed">
      <p>{{ $t('order.listV2.approveTip', {data: isCanApproveList.length }) }}</p>
      <!-- 内容主体区域 -->
      <el-form :model="saveForm" :rules="saveFormRules" ref="saveFormRef" label-position="top">
        <el-form-item :label="$t('common.label.approvalResult')" prop="approveResult">
          <el-input type="textarea" maxlength="500" :rows="5" :placeholder="$t('order.listV2.approveResult')" v-model="saveForm.approveResult"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" plain @click="approveSubmit(false)">{{$t('common.base.refuse')}}</el-button>
        <el-button type="primary" @click="approveSubmit(true)">{{$t('common.base.agree')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash';
import Page from '@model/Page';
import moment from 'moment';
import AuthMixin from '@src/mixins/authMixin';
import AuthUtil from '@src/util/auth';
import AuthEnum from '@model/enum/AuthEnum.ts';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import { formatDate } from 'pub-bbx-utils';
import { isOpenData } from '@src/util/platform';
import { safeNewDate } from '@src/util/time';
import { OrderExport } from '@src/api/Export';
import { getRootWindow } from '@src/util/dom';
import AdvancedSearch from '@src/component/AdvancedSearch/index.vue';
import DeliverGoodsDialog from 'src/modules/linkc/order/component/DeliverGoodsDialog.vue';
import OnsiteServicesDialog from 'src/modules/linkc/order/component/OnsiteServicesDialog.vue';
import EditOrderDialog from 'src/modules/linkc/order/component/EditOrderDialog.vue';
import LogisticsInfoDialog from 'src/modules/linkc/order/component/LogisticsInfoDialog.vue';
import OrderApproveDialog from 'src/modules/linkc/order/component/OrderApproveDialog.vue';
import { queryOrderList, cancelOrder, refundApprove, getRefundApproveAuth} from '@src/api/PortalApi.ts';
import { orderFields, formatFields } from '@src/modules/linkc/field.js';
import { getOssUrl } from '@src/util/assets'
import { defaultTableData } from '@src/util/table'
const goodsDefault = getOssUrl('/goodsDefault.png');
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
const payIcon1 = getOssUrl('/pay_icon1.png');
const payIcon2 = getOssUrl('/pay_icon2.png');
const payIcon3 = getOssUrl('/pay_icon3.png');
import i18n from '@src/locales';
const refundStatus = [
  {
    color: "#FFAE00",
    status: i18n.t('common.base.usualStatus.approving')
  },
  {
    color: "#00C853",
    status: i18n.t('order.listV2.refunded')
  },
  {
    color: "#FF4D4F",
    status: i18n.t('common.base.usualStatus.rejected')
  },
]
export default {
  mixins: [AuthMixin],
  components: {
    AdvancedSearch, // 新版本高级筛选
    DeliverGoodsDialog,
    OnsiteServicesDialog,
    EditOrderDialog,
    LogisticsInfoDialog,
    BaseSearchDrawer, // 老版本高级筛选
    BaseSearchPanel,
    OrderApproveDialog,
  },
  data() {
    return {
      defaultTableData,
      loading: false,
      page: new Page(),
      searchModel: {
        keywords: '',
        pageSize: 10,
        pageNum: 1,
        // logisticsState: 0,
      },
      searchCondition: 'order',
      selectState: 0,
      selectStateList: [
        // 头部筛选列表
        { label: this.$t('common.base.all'), value: 0 },
        { label: this.$t('order.detailV2.toBePaid'), value: 1 },
        { label: this.$t('order.detailV2.toBeShipped'), value: 2 },
        { label: this.$t('common.base.usualStatus.delivered'), value: 3 },
        { label: this.$t('common.base.usualStatus.finish'), value: 4 },
        { label: this.$t('common.event.stateProcess.offed'), value: 5 },
        { label: this.$t('order.listV2.afterSales'), value: 6 },
      ],
      multipleSelection: [],
      multipleSelectionPanelShow: false,
      goodsDefault,
      tableContainerHeight: '440px',
      selectedLimit: 500,
      payIconList: [payIcon1, payIcon2, payIcon3],
      visible: false,
      columnNum: 1,
      advancedSearchParams: {},
      OrderExport,
      currentPageSelect: [],
      hiddenScrollbar: false,
      // 限制宽度
      maximumWidth: 1280,
      batchApproveDialog: false,
      saveFormRules: {
        approveResult: [{ required: true, message: this.$t('order.listV2.approveResult1'), trigger: 'blur' }],
      },
      saveForm: {
        approveResult: '',
      },
      refundArr: [0, 1, 2],
      isCanApproveList: [],
      batchApproveAuth: false,
      orderMainBtns: [{
        name: this.$t('goods.component.expressDelivery'),
        key: 'ExpressDelivery',
        show: ({item}) => {
          if (!(this.editedPermission && item.refundState != 1 && item.refundState !== 0)) return false
          return (item.logisticsState === 2
                || item.logisticsState === 3)
                && !this.isAllServices(item)
        },
        click: ({item}) => {
          if(!item.underApproval) this.openDialog('deliver', item)
        },
        tooltip: {
          show: ({item}) => item.underApproval,
          content: this.$t('order.tips.tooltipText2')
        }
      }, {
        name: this.$t('task.setting.taskTypeSetting.manage.industryNames.name7'),
        key: 'OnSiteService',
        show: ({item}) => {
          if (!(this.editedPermission && item.refundState != 1 && item.refundState !== 0)) return false
          return item.logisticsState === 2 || item.logisticsState === 3
        },
        click: ({item}) => {
          if(!item.underApproval) this.openDialog('services', item)
        },
        tooltip: {
          show: ({item}) => item.underApproval,
          content: this.$t('order.tips.tooltipText1')
        }
      }, {
        name: this.$t('common.base.approve'),
        key: 'Approve',
        show: ({item}) => {
          return item.refundApproveBtn
        },
        click: ({item}) => {
          this.approve(item)
        }
      }, {
        name: this.$t('common.base.detail'),
        key: 'OrderDetail',
        click: ({item}) => {
          this.handleOpenOrderMenuTab(item)
        }
      }]
    };
  },
  filters: {
    formatTime: function (value) {
      if (!value) return;

      return moment(value).format('YYYY-MM-DD HH:mm:ss');
    },
  },
  computed: {
    searchFieldInfo() {
      const fields = formatFields(orderFields) || [];

      fields.forEach(v => {
        if (v.fieldName === 'originType') {
          if (this.partsVersion) {
            v.setting.dataSource = [
              {
                text: this.$t('common.form.type.material'),
                value: 3,
              },
              {
                text: this.$t('common.fields.serviceName.displayName'),
                value: 2,
              },
            ];
          } else {
            v.setting.dataSource = [
              {
                text: this.$t('common.base.sparePart'),
                value: 1,
              },
              {
                text: this.$t('common.label.serviceItem'),
                value: 2,
              },
            ];
          }
        }
      });

      return fields;
    },
    selectedIds() {
      return this.multipleSelection.map(p => p.orderId);
    },
    noDataHeight() {
      let height = this.tableContainerHeight.split('px')[0];

      return `${height - 40}px`;
    },
    exportColumns() {
      const exportColumns = orderFields;
      exportColumns.forEach(v => {
        v.label = v.displayName;
        v.exportAlias = v.fieldName;
      });

      let arr = [
        {
          label: this.$t('event.detail.text3'),
          value: 'goodsExport',
          columns: exportColumns,
        },
      ];
      return arr;
    },
    // 编辑权限
    editedPermission() {
      return AuthUtil.hasAuth(
        this.globalLoginUserAuth,
        AuthEnum.SHIP_COMPLETE_ORDER
      );
    },
    // 导出权限
    exportPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.EXPORT_ORDER);
    },
    placeholder() {
      return this.searchCondition === 'order'
        ? this.$t('order.placeHolder.infoSearch')
        : this.$t('order.placeHolder.productInfo');
    },
    // 备件版本，灰度开启取备件3.0即物料，没有开启取备件2.0
    partsVersion() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.cloudwarehouse ?? true;
    },
  },
  mounted() {
    this.handleSearch();
    this.getAuth()
    let that_ = this;
    // 监听切换后需要重新计算列表高度
    window.addEventListener('message', event => {
      const { action, data } = event.data;
      if (action == 'shb.frame.activatedPage') {
        that_.$nextTick(() => {
          this.hiddenScrollbar = !!(
            this.$refs.orderTableRef.offsetWidth >= this.maximumWidth
          );
          that_.knowTableContainerHeight();
        });
      }
    });
    this.$nextTick(() => {
      this.knowTableContainerHeight();
      window.onresize = _.debounce(() => {
        this.hiddenScrollbar = !!(
          this.$refs.orderTableRef.offsetWidth >= this.maximumWidth
        );
        that_.knowTableContainerHeight();
      }, 500);
    });
  },
  methods: {
    async getAuth() {
      const { code, data, message } = await getRefundApproveAuth();
      if (code !== '200') return this.$message.error();
      this.batchApproveAuth = data
    },
    batchApprove() {
      let isCanApproveList = this.multipleSelection.filter(item => item.refundApproveBtn) || []
      this.isCanApproveList = isCanApproveList
      if(this.multipleSelection.length == 0) return this.$message.error(this.$t('order.listV2.selectApproveOrder'));

      if(isCanApproveList.length == 0) return this.$message.error(this.$t('order.listV2.noApproveOrder'));
      // 需要将列表中没有审批按钮的过滤掉

      this.batchApproveDialog = true
    },
    approveSubmit(approveResult) {
      this.$refs.saveFormRef.validate(async valid => {
        if (!valid) return    
        // 批量审批接口调用
        let refundIdList = this.isCanApproveList.map(item => item.refundId)
        let params = {
          approveResult,
          refundIdList,
          approveRemark: this.saveForm.approveResult
        }
        const { code, data, msg } = await refundApprove(params);
        if (code !== '200') return this.$message.error(msg);
        this.batchApproveDialog = false
        this.reloadPage()
      })
    },
    saveDialogClosed() {
      this.$refs.saveFormRef.resetFields()
    },
    approve(item) {
      this.$refs.orderApproveDialog.openDialog(item.refundId)
      this.$refs.orderApproveDialog.visible = true
    },
    async handleSearch() {
      try {
        this.loading = true;

        const params = {
          ...this.searchModel,
          ...this.advancedSearchParams,
        };
        if (params.orderTime) {
          const arr = params.orderTime.split('-');
          params.orderStartTime = arr[0];
          params.orderStartEnd = arr[1];
          delete params.orderTime;
        }
        if (this.searchCondition !== 'order') {
          params.commodityKeywords = params.keywords;
          delete params.keywords;
        }
        if (this.selectState === 0) delete params.logisticsState;

        const { code, data } = await queryOrderList(params);

        if (code !== '200') {
          this.loading = false;
          this.page = this.$options.data.call(this).page;
          return this.$message.error(this.$t('goods.tips.queryListFailed'));
        }

        const { pageNum, list, total, pageSize } = data;
        [
          this.page['list'],
          this.page['totalElements'],
          this.page['pageNum'],
          this.page['pageSize'],
        ] = [list, total, pageNum, pageSize];

        this.loading = false;
        this.handleActiveCheckbox();
      } catch (error) {
        this.loading = false;
        console.error('fetch order list error', error);
      }
    },
    reloadPage() {
      this.multipleSelection = [];
      this.handleSearch();
    },
    resetParams() {
      window.TDAPP.onEvent(this.$t('order.listV2.orderManagement1'));
      this.searchModel = this.$options.data.call(this).searchModel;
      this.selectState = this.$options.data.call(this).selectState;
      this.searchCondition = this.$options.data.call(this).searchCondition;
      this.page = this.$options.data.call(this).page;

      // 新版本方法
      // this.$refs.advancedSearchRef.resetField();
      // this.$refs.advancedSearchRef.search();
      this.$refs.searchPanel?.initFormVal();
      this.advancedSearchParams = {};
      this.handleSearch();
    },
    handleExport(exportAll) {
      let ids = [];
      let fileName = this.$t('order.listV2.orderData', {data1: formatDate(safeNewDate(), 'YYYY-MM-DD')});
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(this.$t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanelRef.open(ids, fileName);
      this.$refs.exportPanelRef.visible = false;
      this.$refs.exportPanelRef.exportData(true);
    },
    // 新版本高级搜索 ——> 点击搜索按钮
    // handleAdvancedSearch(searchModel) {
    //   const { systemConditions } = searchModel;
    //   const params = {};
    //   systemConditions.forEach(v => (params[v.property] = v.value));
    //   this.searchModel = { ...this.searchModel, ...params };
    //   this.handleSearch();
    // },
    // 老版本高级搜索 ——> 点击搜索按钮
    handleAdvancedSearch() {
      this.searchModel.pageNum = 1;
      // 获取高级搜索参数
      this.advancedSearchParams = this.$refs.searchPanel?.buildParams() || {};
      this.handleSearch();
    },
    panelSearchAdvancedToggle() {
      this.visible = true;
      window.TDAPP.onEvent(this.$t('goods.list.advancedSearchEvent'));
    },
    handleStateChange(val) {
      this.selectState = val;
      this.searchModel.pageNum = 1;
      this.searchModel.logisticsState = val;
      this.handleSearch();
    },
    /** 设置高级搜索展示列数 */
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      if (type === 'search') {
        window.TDAPP.onEvent(this.$t('order.listV2.orderManagement2'));
        return;
      }
      if (type === 'moreAction') {
        window.TDAPP.onEvent(this.$t('order.listV2.orderManagement3'));
        return;
      }
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight() {
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 10;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        min =
          window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 12;
        if (!this.hiddenScrollbar) min = min - 16;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`);
    },
    handleActiveCheckbox() {
      this.page.list?.forEach(v => {
        const isExist = this.multipleSelection.some(
          f => f.orderId === v.orderId
        );
        if (isExist) v.checked = true;
      });
    },
    handleCurrentChange(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.handleSearch();
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.handleSearch();
    },
    handleCheckboxChange(i) {
      const selection = this.page?.list?.[i];

      const index = this.multipleSelection.findIndex(
        v => v.orderId === selection?.orderId
      );
      if (index > -1) {
        this.multipleSelection.splice(index, 1);
      } else {
        this.multipleSelection.push(selection);
      }
    },
    getOrderStatusStr(value) {
      switch (value) {
        case 1:
          return this.$t('order.detailV2.toBePaid');
        case 2:
          return this.$t('order.detailV2.toBeShipped');
        case 3:
          return this.$t('common.base.usualStatus.delivered');
        case 4:
          return this.$t('common.base.usualStatus.finish');
        case 5:
          return this.$t('common.event.stateProcess.offed');
        default:
          return '';
      }
    },
    getOrderStatusColor(value) {
      switch (value) {
        case 1:
          return 'background: #FF7043';
        case 2:
          return 'background: #0092EA';
        case 3:
          return 'background: #26C6DA';
        case 4:
          return 'background: #00C853';
        case 5:
          return 'background: #BDBDBD';
        default:
          return '';
      }
    },
    getRefundStatusColor(value) {
      return refundStatus[value]?.color || ''
    },
    getRefundStatusStr(value) {
      return refundStatus[value]?.status || ''
    },
    getPayTypeStr(value) {
      switch (value) {
        case 1:
          return this.$t('order.detailV2.weChatPayment');
        case 2:
          return this.$t('order.detailV2.alipayPayment');
        case 3:
          return this.$t('order.listV2.limitSettlement');
        default:
          return '';
      }
    },
    getOriginType(value) {
      if (!value) return '';

      if (value === 1) return this.$t('common.base.sparePart');
      if (value === 2) return this.$t('common.fields.serviceName.displayName');

      return this.$t('common.form.type.material');
    },
    getServiceTypeStr(value) {
      if (value === 1) {
        return this.$t('goods.component.expressDelivery');
      } else if (value === 2) {
        return this.$t('task.setting.taskTypeSetting.manage.industryNames.name7');
      } else if (value === 3) {
        return this.$t('goods.component.serviceMethod');
      }

      return '-';
    },
    // 截取当前数据到小数点后两位
    numFilter(value) {
      if (!value) return '';

      let tempVal = parseFloat(value).toFixed(3);
      let realVal = tempVal.substring(0, tempVal.length - 1);

      return realVal;
    },
    handleOpenGoodsMenuTab(row) {
      if (!row.id) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageGoodsDetail,
        key: row.id,
        titleKey: ` - ${row.commodityName}`,
        params: `id=${row.id}`,
        fromId,
      });
    },
    handleOpenOrderMenuTab(row) {
      if (!row.orderId) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageOrderDetailV2,
        key: row.orderId,
        // titleKey: row.orderNum,
        params: `id=${row.orderId}`,
        fromId,
      });
    },
    async handleCancelOrder(id) {
      try {
        if (!(await this.$platform.confirm(this.$t('order.listV2.cancelCommfirm')))) return;
        const { code, data } = await cancelOrder({
          orderId: id,
        });

        if (code !== '200' || !data) {
          return this.$message.error(this.$t('order.tips.cancelFailed'));
        }

        this.$message.success(this.$t('order.tips.cancelSuccess'));
        setTimeout(() => {
          this.handleSearch();
        }, 1000);
      } catch (error) {
        console.error('handleGetParcelList error', error);
      }
    },
    openDialog(action, row) {
      if (action === 'edit') {
        window.TDAPP.onEvent(this.$t('order.detailV2.orderManagement1'));

        let state = row.logisticsState;
        if (row.payType === 3 && row.logisticsState === 2) state = 1;
        const isShow = !this.isAllServices(row);
        this.$refs.editOrderRef.open(row.orderId, state, isShow);
      }

      if (action === 'logistics') {
        window.TDAPP.onEvent(this.$t('order.listV2.orderManagement4'));
        this.$refs.logisticsInfoRef.open(row.orderId);
      }

      if (action === 'deliver') {
        window.TDAPP.onEvent(this.$t('order.detailV2.orderManagement2'));
        this.$refs.deliverGoodsRef.open(row.orderId, row.firstDeliverGoods);
      }

      if (action === 'services') {
        window.TDAPP.onEvent(this.$t('order.detailV2.orderManagement3'));
        this.$refs.onsiteServicesRef.open(row.orderId, row.memberPhone);
      }
    },
    /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.page.totalElements > max
        ? this.$t('common.base.exportModal.oversizeTips', {size: '5000'})
        : null;
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const exportAll = !ids || !ids.length;

      const searchParams = {
        ...this.searchModel,
        ...this.advancedSearchParams,
      }
      const params = {
        checked:
          'orderNum,placeOrderDate,logisticsState,payType,payAmount,memberName,address,shipMethod,logistics,taskNo,commodityName,originCategory,serviceType',
        idList: exportAll ? '' : this.selectedIds.join(','),
        exportSearchModel: JSON.stringify(searchParams),
        dataTotal: exportAll
          ? this.page.totalElements
          : this.selectedIds.length,
      };

      return params;
    },
    isAllServices(row) {
      if (!row?.commodityInfoList?.length) return false;

      return row.commodityInfoList.every(v => v.originType === 2);
    },
    previewImg(url, urls = []) {
      if (typeof urls !== 'object') {
        urls = [];
      }

      this.$previewElementImg(url, urls);
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@src/assets/scss/common-list.scss';

.order-list-container {
  height: 100%;
  padding: 12px;
  // min-width: 1280px;
  overflow: auto;

  .order-list-search-group-container {
    padding: 16px;
    border-radius: 4px;
    .base-search {
      background: #fff;
      border-radius: 3px;
      font-size: 14px;
      display: flex;
      justify-content: space-between;

      .order-list-base-search-group {
        display: flex;
        justify-content: space-between;

        .el-input {
          width: 400px;
          border-radius: 0;
        }

        a {
          line-height: 33px;
        }
      }

      .advanced-search-visible-btn {
        font-size: 14px;
        line-height: 31px;
        @include fontColor();
        border-color: $color-primary;
        background: #fff;
        padding: 0 13px;
        white-space: nowrap;
        &:hover {
          cursor: pointer;
        }

        i {
          font-size: 16px;
        }
      }
    }
  }

  .task-list {
    &-header {
      background: #ffffff;
      box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.06);
      border-radius: 4px;
      margin-bottom: 12px;
      border-top: none;

      &-search {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        align-items: flex-start;
        // padding: 16px;
        .advanced-search-visible-btn {
          // width: 98px;
          height: 32px;
          border-radius: 4px;
          font-size: 14px;
          @include fontColor();
          line-height: 32px;
          text-align: center;
          cursor: pointer;
          white-space: nowrap;
          margin-left: 0;

          i {
            font-size: 16px;
          }
        }

        .base-search-group {
          .el-input {
            width: 400px !important;
            input {
              border-radius: 4px 0 0 4px;
            }
          }
        }

        .customize-filter-view {
          margin-bottom: 16px;
        }
      }

      &-nav {
        padding-top: 16px;
        .task-filter-item {
          display: flex;
        }
        > div {
          position: relative;
          cursor: pointer;
          // border-top: 1px solid #F5F5F5;
          .state {
            padding-top: 4px;
            width: 100px;
            // background-color: #FAFAFA;
          }
          .element-icon {
            position: absolute;
            right: 12px;
            top: 6px;
            span {
              color: rgba(0, 0, 0, 0.65);
            }
          }
          .list {
            // width: 90%;
            flex: 1;
            overflow: hidden;
            // height: 30px;
            .list-item {
              > div {
                // padding-left: 11px;
                font-size: 13px;
                max-width: 160px;
                overflow-y: hidden;
                color: #595959;
                padding: 4px 8px;
                white-space: nowrap;
                overflow: hidden;
                // margin: 0 8px 4px 0;
              }
            }
          }
        }
      }
    }
  }

  .task-list-header-search {
    form {
      justify-content: flex-end;
    }
  }

  .task-padding-0 {
    padding: 0 !important;
  }

  .order-list-section {
    margin-top: 12px;
    padding-top: 0;
    background: #fff;
    border-radius: 4px;

    .operation-bar-container {
      border-radius: 4px 4px 0 0;
      display: flex;
      justify-content: space-between;
      padding: 16px 16px 0;

      .el-dropdown-btn {
        padding: 0 15px;
        line-height: 31px;
        display: inline-block;
        background: $color-primary-light-9;
        color: $text-color-primary;
        outline: none;
        margin-left: 5px;
        .iconfont {
          margin-left: 5px;
        }

        &:hover {
          cursor: pointer;
          color: #fff;
          background: $color-primary;
        }
      }
    }

    .order-table-container {
      overflow-x: scroll;
      overflow-y: hidden;
      width: 100%;
    }

    /*去除滚动条*/
    .hidden-scrollbar::-webkit-scrollbar {
      display: none;
    }

    .order-table {
      width: 100%;
      min-width: 1182px;
      font-size: 14px;
      position: relative;

      &-row {
        display: flex;
      }

      &-col {
        height: 100%;
        line-height: 40px;
        text-align: center;
        width: 120px;
      }

      &-col:first-child {
        width: calc(100% - 360px - 540px);
        text-align: left;
        padding-left: 12px;
      }

      &-col:nth-child(3),
      &-col:nth-child(4) {
        width: 200px;
      }

      &-col:last-child {
        width: 140px;
      }

      .order-btn {
        cursor: pointer;
        // color: $color-primary;
        margin-left: 12px;
        white-space: nowrap;
        & + .order-btn {
          margin-right: 12px;
        }
      }

      &-header {
        width: 100%;
        height: 40px;
        background: #fafafa;
        color: #262626;
        font-weight: 500;
      }

      &-card {
        width: 100%;
        background: #ffffff;
        box-shadow: 0 4px 30px 0 rgb(27 25 86 / 10%);
        margin-top: 12px;

        &-header {
          height: 32px;
          background: #fafafa;
          color: #8c8c8c;
          display: flex;
          align-items: center;
          justify-content: space-between;

          > div {
            height: 100%;
            line-height: 32px;
            text-align: center;
          }

          div:last-child {
            text-align: right;

            span {
              margin-right: 16px;
              cursor: pointer;
            }
          }

          &-content {
            display: flex;
            align-items: center;
            white-space: nowrap;
            > div {
              margin-right: 24px;
            }

            div:first-child {
              text-align: left;

              .el-checkbox {
                margin: 0 8px 0 12px;
              }
            }

            .logistics-state,
            .pay-type {
              display: flex;
              align-items: center;

              span {
                margin: 0 !important;
                cursor: default !important;
              }
            }

            .logistics-state {
              padding-left: 0;
              justify-content: center;

              i {
                font-size: 16px;
                color: red;
                cursor: pointer;
                margin-right: 6px;
              }
            }

            .pay-type {
              margin-right: 0;
              img {
                height: auto;
                margin-right: 3px;
              }
            }

            .order-status {
              display: inline-block;
              width: 52px;
              height: 22px;
              line-height: 22px;
              text-align: center;
              background: #00c853;
              border-radius: 11px;
              font-size: 12px;
              color: #fff;
              padding: 0px 6px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            .refund-status {
              margin-top: 5px;
              margin-left: 5px
            }
          }
        }

        &-main {
          width: 100%;

          .order-table-col {
            height: 100%;
            text-align: center;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: #262626;

            .card-item {
              height: 80px;
              display: flex;
              justify-content: center;
              align-items: center;
              line-height: 20px;
            }
          }

          .order-table-col:nth-child(6) {
            .card-item {
              flex-direction: column;

              span:last-child {
                color: $color-primary-light-6;
                margin-top: 5px;
                cursor: pointer;
              }
            }
          }

          .order-table-col:first-child {
            justify-content: flex-start;
            align-items: flex-start;
            // width: calc(100% - 360px - 540px);

            .card-item {
              width: 100%;

              .el-image {
                width: 56px;
                height: 56px;
                cursor: pointer;
                margin: 0 16px 0 12px;
              }

              div {
                display: flex;
                flex-direction: column;
                justify-content: flex-start;
                width: calc(100% - 84px);
                line-height: 20px;

                span {
                  width: 100%;
                  text-align: left;
                  overflow: hidden;
                  // @include text-ellipsis;
                }

                span:last-child {
                  color: $color-primary-light-6;
                  margin-top: 8px;
                  cursor: pointer;
                }
              }
            }
          }

          .order-table-col:last-child {
            color: $color-primary-light-6;
            cursor: pointer;

            .card-item {
              line-height: 0px;
            }

            .el-tooltip {
              color: #8c8c8c;
            }

            div {
              // height: 30px;
              flex-wrap: wrap;
            }

            span {
              margin-right: 10px;
            }
          }
        }

        &-footer {
          width: 100%;
          height: 40px;
          background: #ffffff;
          color: #8c8c8c;
          border-top: 1px solid #e8e8e8;
          font-weight: 400;
          display: flex;
          align-items: center;

          i {
            font-size: 14px;
            margin: 0 14px;
          }

          span {
            margin-right: 14px;
          }

          .remarks {
            color: #faad14;
          }
        }
      }

      &-card:last-child {
        margin-bottom: 10px;
      }

      &-no-data {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      }
    }

    .table-footer {
      bottom: -20px;
    }
  }

  .flex-end {
    display: flex;
    justify-content: flex-end;
  }
}

.order-list-container ::v-deep .input-with-append-search .el-input input {
  border-radius: 0;
}
</style>
